package com.weblog.article.controller;

import com.weblog.article.dao.CategoryDao;
import com.weblog.model.article.Category;
import com.weblog.article.service.CategoryService;
import com.weblog.model.article.output.CategoryVo;
import constants.RedisKey;
import entity.PageResult;
import entity.Result;
import entity.ResultMessage;
import entity.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * category控制器层
 *
 * @author Administrator
 */
@RestController
@CrossOrigin
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedisTemplate jsonRedisTemplate;

    @Autowired
    private CategoryDao categoryDao;


    /**
     * 增加
     *
     * @param category
     */
    @PostMapping
    public Result addCategory(@RequestBody Category category) {
        int flag = categoryService.addCategory(category);
        if (flag == 2) {
            return new Result(false, StatusCode.ACCESSERROR, ResultMessage.ACCESS_ERROR);
        } else if (flag == 0) {
            return new Result(false, StatusCode.REPERROR, ResultMessage.CATEGORY_EXISTED);
        }
        return new Result(true, StatusCode.OK, ResultMessage.SAVE_SUCCESS);
    }

    /**
     * 分页+多条件查询
     *
     * @param searchMap 查询条件封装
     * @param page      页码
     * @param size      页大小
     * @return 分页结果
     */
    @PostMapping(value = "/search/{page}/{size}")
    public Result PageBySearch(@RequestBody Map searchMap, @PathVariable int page, @PathVariable int size) {
        Page<Category> pageList = categoryService.PageBySearch(searchMap, page, size);
        return new Result(true, StatusCode.OK, ResultMessage.QUERY_SUCCESS, new PageResult<Category>(pageList.getTotalElements(), pageList.getContent()));
    }


    /**
     * 根据ID查询实体
     *
     * @param id ID
     * @return
     */
    @GetMapping(value = "/{id}")
    public Result findById(@PathVariable String id) {
        Category category = categoryService.findById(id);
        if (category == null) {
            return new Result(false, StatusCode.ERROR, ResultMessage.CATEGORY_NOT_FOUND);
        }
        return new Result(true, StatusCode.OK, ResultMessage.QUERY_SUCCESS, category);
    }


    /**
     * 修改
     *
     * @param category
     */
    @PutMapping(value = "/{id}")
    public Result update(@RequestBody Category category, @PathVariable String id) {
        category.setId(id);
        int flag = categoryService.update(category);
        if (flag == 2) {
            return new Result(false, StatusCode.ACCESSERROR, ResultMessage.ACCESS_ERROR);
        }
        return new Result(true, StatusCode.OK, "修改成功");
    }

    /**
     * 删除 (state改为1)
     *
     * @param id
     */
    @PutMapping(value = "/{id}/{isparent}")
    public Result delete(@PathVariable String id, @PathVariable String isparent) {
        int flag = categoryService.deleteById(id, isparent);
        if (flag == 2) {
            return new Result(false, StatusCode.ACCESSERROR, ResultMessage.ACCESS_ERROR);
        }
        return new Result(true, StatusCode.OK, ResultMessage.DELETE_SUCCESS);
    }


    /**
     * 获取封装树形数据
     *
     * @return
     */
    @PostMapping("/tree")
    public Result fetchCategoryTree() {
        if (jsonRedisTemplate.opsForList().range(RedisKey.WEBLOG_CATEGORY_TREE, 0, -1).size() > 0) {
            return new Result(true, StatusCode.OK, ResultMessage.QUERY_SUCCESS, (List<Category>) jsonRedisTemplate.opsForList().index("weblog_category_tree", 0));
        }
        //缓存不存在
        List<Category> categoryTree = categoryService.fetchCategoryTree();
        jsonRedisTemplate.opsForList().leftPush(RedisKey.WEBLOG_CATEGORY_TREE, categoryTree);
        return new Result(true, StatusCode.OK, ResultMessage.QUERY_SUCCESS, categoryTree);
    }

    /**
     * 根据条件查询
     *
     * @param searchMap
     * @return
     */
    @RequestMapping(value = "/search", method = RequestMethod.POST)
    public Result findSearch(@RequestBody Map searchMap) {
        return new Result(true, StatusCode.OK, "查询成功", categoryService.findSearch(searchMap));
    }


    /**
     * 根据ID查询分类名 (客户端使用)
     *
     * @param id ID
     * @return
     */
    @GetMapping(value = "/client/{id}")
    public Result findCnameById(@PathVariable String id) {
        String cname = categoryDao.findCnameById(id);
        System.out.println(cname);
        if (cname == null || "".equals(cname)) {
            return new Result(false, StatusCode.ERROR, ResultMessage.CATEGORY_NOT_FOUND);
        }
        return new Result(true, StatusCode.OK, ResultMessage.QUERY_SUCCESS, cname);
    }


    /**
     * 根据clevel查询分类id和分类名 (客户端使用)
     *
     * @param clevel
     * @return
     */
    @GetMapping(value = "/client/home/{clevel}")
    public Result findCidsAndCnamesByClevel(@PathVariable("clevel") int clevel) {
        try {
            List<Category> categories = categoryDao.findCategoriesByClevel(clevel);
            List<String> cids = new ArrayList<>();
            List<String> cnames = new ArrayList<>();
            for (Category category : categories) {
                cids.add(category.getId());
                cnames.add(category.getCname());
            }
            CategoryVo vo=new CategoryVo();
            vo.setCids(cids);
            vo.setCnames(cnames);
            return new Result(true, StatusCode.OK, ResultMessage.QUERY_SUCCESS, vo);

        } catch (Exception e) {
            return new Result(false, StatusCode.ERROR, ResultMessage.CATEGORY_NOT_FOUND);
        }
    }

    /**
     * 根据id查询分类等级
     *
     * @param cid
     * @return
     */
    @GetMapping("/client/clevel/{cid}")
    public Result getLevelById(@PathVariable("cid") String cid) {
        int clevel = categoryService.findClevelById(cid);
        return new Result(true, StatusCode.OK, ResultMessage.QUERY_SUCCESS, clevel);

    }


    @GetMapping("/client/count")
    public Result countTotal() {
        long count = categoryService.count();
        return new Result(true, StatusCode.OK, ResultMessage.QUERY_SUCCESS, count);

    }


}
